package com.system.connect.springboot_flowers.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.connect.springboot_flowers.entity.Likes;
import com.system.connect.springboot_flowers.entity.Originalposts;
import com.system.connect.springboot_flowers.entity.Users;
import com.system.connect.springboot_flowers.service.ILikesService;
import com.system.connect.springboot_flowers.service.IOriginalpostsService;
import com.system.connect.springboot_flowers.service.IUsersService;
import com.system.connect.springboot_flowers.utils.R;
import com.system.connect.springboot_flowers.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 点赞表 前端控制器
 * </p>
 *
 * @author yang
 * @since 2025-01-13
 */
@RestController
@RequestMapping("/api/likes")
public class LikesController {

    @Autowired
    private ILikesService likesService;

    @Autowired
    private IUsersService userService;

    @Autowired
    private IOriginalpostsService postsService;

    @PostMapping("/{post_id}") // 确保路径与前端请求匹配
    public R like(@PathVariable("post_id") Integer postsid) {
        //判断是否已经点赞
        Likes likes = new Likes();
        Users user = userService.getById(TokenUtils.getUser());//获取当前用户
        Originalposts post = postsService.getById(postsid);

        likes.setSenderId(user.getUserId());
        likes.setReceiverId(post.getUserId());
        likes.setTargetType("posts");
        likes.setTargetId(postsid);

        Likes like = likesService.getOne(new QueryWrapper<>(likes));
        if (like==null){
            likesService.save(likes);
            return R.success("点赞成功");
        }
        if (like.getIsDelete()==false){
            System.out.println(like.getIsDelete());
            like.setIsDelete(true);
            likesService.updateById(like);
            return R.success("取消点赞成功");
        }else{
            System.out.println(like.getIsDelete());
            like.setIsDelete(false);
            likesService.updateById(like);
            return R.success("点赞成功");
        }

    }

}
